import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header


class Email(object):

    def __init__(self, host, fromAddress, password):
        self.host = host
        self.fromAddress = fromAddress
        self.password = password

    def _Send(self, toAddress, messageObject):
        try:
            server = smtplib.SMTP(self.host)
            server.login(self.fromAddress, self.password)
            server.sendmail(self.fromAddress, toAddress, messageObject.as_string())
            print("邮件发送成功 to", toAddress)
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")


    def SendTextMail(self, toAddress, subject, content):
        #
        message = MIMEText(content, 'plain', 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')
        message['From'] = self.fromAddress
        message['To'] = toAddress
        #
        self._Send(toAddress, message)


    def SendAttachment(self, toAddress, subject, content, path, filename):
        #
        message = MIMEMultipart()
        message.attach(MIMEText(content, 'plain', 'utf-8'))
        message['Subject'] = Header(subject, 'utf-8')
        message['From'] = self.fromAddress
        message['To'] = toAddress
        #
        attchment = MIMEText(open(path + filename, 'rb').read(), 'base64', 'utf-8')
        attchment["Content-Type"] = 'application/octet-stream'
        attchment["Content-Disposition"] = 'attachment; filename="' + filename + '"'
        message.attach(attchment)
        #
        self._Send(toAddress, message)


if __name__ == '__main__':
    # 163邮箱服务器地址，端口默认为25

    email = Email('smtp.126.com', "kkwood@126.com", "Kirk_1984")
    # email.SendTextMail("kkwood@126.com", "Test5", "TestContent")

    path = "D:/Data/TagStatistics/"
    filename = "test.txt"
    email.SendAttachment("kkwood@126.com", "Test4", "TestContent", path, filename)